package ddbs;

public class MSG {
    // type: ConfirmClientId, workload(sched)
    String type;
    String status;
    int id;
    int len;
    String content;

    private void init(String type, String status, int id, int len,
            String content) {
        this.type = type;
        this.status = status;
        this.id = id;
        this.len = len;
        this.content = content;
    }

    public MSG(String type, String status, int id, int len, String content) {
        init(type, status, id, len, content);
    }

    public MSG(int length, String contents) throws Exception {
        int idx = -1;
        for (int i = 0; i < 4; ++i) {
            idx = contents.indexOf("!", idx + 1);
            if (idx < 0) {
                System.out.println("i=" + i + " idx=" + idx + " length="
                        + length);
                if (length > 20) {
                    for (int j = 0; j < 20; ++j)
                        System.out.print(contents.charAt(j));
                }
                System.out.println();
                throw new Exception();
            }
        }

        String msgDetails[] = contents.substring(0, idx).split("!");
        // System.out.println("msgDetails lenth= "+msgDetails.length);

        if (msgDetails.length < 4) {
            throw new Exception();
        }
        String c = contents.substring(idx + 1);
        init(msgDetails[0], msgDetails[1], Integer.parseInt(msgDetails[2]),
                Integer.parseInt(msgDetails[3]), c);
    }

    void show() {
        System.out.println("MSG type=" + type);
        System.out.println("MSG status=" + status);
        System.out.println("MSG id=" + id);
        System.out.println("MSG len=" + len);
        int length = len;
        if (length > 200) length = 200;
        System.out.println("MSG contents=" + content.substring(0,length));

    }
}
